﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Data;
using System.Globalization;

namespace Yorrick.Common
{
    public class DateTimeFormatter : IValueConverter
    {

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value != null)
            {
                DateTime? date = value as DateTime?;

                if (date == null)
                {
                    throw new InvalidCastException("Can only format DateTime with DateTimeFormatter");
                }

                string retval = date.Value.ToString(parameter.ToString(), culture);

                return retval;
            }
            else
            {
                return null;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            DateTime retval;
            bool succeeded = DateTime.TryParse(value.ToString(), culture, DateTimeStyles.None, out retval);

            if (succeeded)
            {
                return retval;
            }
            else
            {
                return null;
            }
        }

        #endregion
    }
} 

